package com.ly.publisher.config;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * 定义 ReturnCallback
 *
 * @author 23087
 */
@Slf4j
@AllArgsConstructor
@Configuration
/**
 * 配置MQ的相关属性
 */
public class MqConfig {

    /**
     * RabbitTemplate用于发送和接收消息
     */
    private final RabbitTemplate rabbitTemplate;

    /**
     * 在该类被Spring容器初始化后执行初始化操作
     */
    @PostConstruct
    public void init(){
        // 设置消息返回的回调函数
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback(){
            /**
             * 当消息无法投递到任何订阅者时触发
             * @param returned 退回的消息对象，包含交换机、路由键、消息内容等信息
             */
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                // 记录退回消息的日志
                log.error("触发 return callback,");
                log.debug("exchange:{}",returned.getExchange());
                log.debug("routingKey:{}",returned.getRoutingKey());
                log.debug("message:{}",returned.getMessage());
                log.debug("replyCode:{}",returned.getReplyCode());
                log.debug("replyText:{}",returned.getReplyText());
            }
        });
    }
}
